package com.zoro.barn.business.service.pp.business.product.service;

import com.zoro.barn.business.service.pp.business.product.dao.BarnProductMapper;
import com.zoro.barn.business.service.pp.business.product.entity.BarnProduct;
import com.zoro.barn.business.service.pp.business.product.entity.BarnProductUser;
import com.zoro.barn.business.service.pp.exceptions.DataIncompleteException;
import com.zoro.barn.business.service.pp.server.SqlServiceService;
import com.zoro.barn.business.service.pp.server.facade.BarnDocumentServerServiceFacade;
import com.zoro.barn.commons.tools.string.IDs;
import com.zoro.barn.dto.documentsql.sql.SqlQueryDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author zhaoxingwu
 */
@Service
public class BarnProductService {

    @Resource
    private BarnProductMapper barnProductMapper;

    private final SqlServiceService sqlServiceService;
    private final BarnDocumentServerServiceFacade barnDocumentServerServiceFacade;

    public BarnProductService(SqlServiceService sqlServiceService, BarnDocumentServerServiceFacade barnDocumentServerServiceFacade) {
        this.sqlServiceService = sqlServiceService;
        this.barnDocumentServerServiceFacade = barnDocumentServerServiceFacade;
    }

    @Transactional(rollbackFor = Exception.class)
    public BarnProduct insert(BarnProduct data) {
        if (StringUtils.isBlank(data.getCreateId())) {
            throw new DataIncompleteException("create id can not be null");
        }
        data.setPid(IDs.uuid());
        data.setCreateDate(new Date());
        this.barnProductMapper.insert(data);
        return data;
    }

    @Transactional(rollbackFor = Exception.class)
    public BarnProduct update(BarnProduct data) {
        if (StringUtils.isAnyBlank(data.getPid(), data.getUpdateId())) {
            throw new DataIncompleteException("pid or update id is null ");
        }
        data.setUpdateDate(new Date());
        this.barnProductMapper.updateById(data);
        return data;
    }

    public List<BarnProduct> query(BarnProductUser product) {
        return this.barnProductMapper.query(product);
    }

    public BarnProduct getById(String pid) {
        return this.barnProductMapper.selectById(pid);
    }

    public int countSqlByProduct(String product) {
        SqlQueryDto dto = new SqlQueryDto();
        dto.setProductId(product);
        SqlQueryDto result = this.sqlServiceService.queryProductSql(dto);
        if (result == null) {
            return 0;
        }
        return result.getSqlCount() == null ? 0 : result.getSqlCount();
    }

    public int countDocumentByProduct(String product) {
        return this.barnDocumentServerServiceFacade.countByProduct(product);
    }
}
